package com.leyou.item.service.impl;

import com.leyou.item.interfaces.pojo.Category;
import com.leyou.item.interfaces.pojo.vo.GoodsPage;
import com.leyou.item.mapper.CategoryMapper;
import com.leyou.item.mapper.GoodsMapper;
import com.leyou.item.service.GoodsService;
import com.leyoucommon.pojo.PageResult;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import tk.mybatis.mapper.entity.Example;
import java.util.ArrayList;
import java.util.List;

/**
 * @version 1.0.0
 * @Author yong.Mr
 * @data 2019-8-9
 */
@Service
@Transactional
public class GoodsServiceImpl implements GoodsService {

    /**
     * 注入GoodsMapper
     */
    @Autowired
    private GoodsMapper goodsMapper;

    /**
     * 注入CategoryMapper
     */
    @Autowired
    private CategoryMapper categoryMapper;

    /**
     * 根据查询条件分页并排序查询商品信息
     * @param key 模糊查询的条件
     * @param saleable 是否上下架
     * @param page 当前页数
     * @param rows 当前页的数据量
     * @return ResponseEntity<PageResult<Goods>>
     */
    @Override
    public PageResult<GoodsPage> queryBrandByPage(String key, Boolean saleable, Integer page, Integer rows) {

        System.out.println("************是否是SQL语句执行失败****************");
        System.out.println("saleable数据是否传入----->:" + saleable );

        // 查询所有的数据
        List<GoodsPage> goodsAll = goodsMapper.queryGoodsByPageAll(key, saleable);

        // 如果 rows = -1 展示所有数据
        if(rows == -1){
            page = 1;
            rows = goodsAll.size();
        }

        // 查询分页的数据
        List<GoodsPage> goods = goodsMapper.queryGoodsByPageSql(key, saleable, page, rows);
        System.out.println("查看数据是否成功----->:**************************-->" + goods.size());

        Example example = new Example(Category.class);
        Example.Criteria criteria = example.createCriteria();
        // 进行语句查询----->查询出商品分类
        List<Integer> list = null;
        for (int i = 0; i < goods.size(); i++) {
            list = new ArrayList<>();
            list.add(goods.get(i).getCid1());
            list.add(goods.get(i).getCid2());
            list.add(goods.get(i).getCid3());
            System.out.println("测试in中的数据----->:" + list.toString());
            criteria.andIn("id", list);
            // 商品分类
            String cname = "";
            List<Category> categories = categoryMapper.selectByExample(example);
            System.out.println("查询出来的商品分类的数据----->:" + categories);
            for (Category category : categories) {
                cname += "-" +category.getName();
            }
            goods.get(i).setCname(cname);
        }

        System.out.println("************是否是SQL语句执行失败****************");

        return new PageResult<GoodsPage>(goodsAll.size(),(goodsAll.size()/goods.size()),goods);
    }
}
